<?php


namespace models\Business;

use Yaf\Registry;
use models\Exception\Business\AdException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\DAO\ModelSqlException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use models\Service\AdService;

class Ad
{
    /**
     * 创建广告
     */
    public static function createAd($parameters = [])
    {
        try {
            $now_date = date('Y-m-d H:i:s', time());
            // $name = "", $img = "", $type = 0, $ad_addr_type = 0,
            // $ad_addr = "", $status = 0, $past_time = "", $order = 0,
            // $created_at = "", $created_by = 0, $updated_at = "", $updated_by = 0
            return AdService::getInstance()->create(
                $parameters['name'],
                str_replace(Registry::get('config')['application']['host'], '', $parameters['img']),
                $parameters['type'],
                $parameters['ad_addr_type'],
                $parameters['ad_addr'],
                isset($parameters['ad_one_pop']) && !empty($parameters['ad_one_pop']) ? $parameters['ad_one_pop'] : 0,
                $parameters['status'],
                isset($parameters['past_time']) ? str_replace('/', '-', $parameters['past_time']) : '0000-00-00 00:00:00',
                isset($parameters['order']) && !empty($parameters['order']) ? $parameters['order'] : 0,
                $now_date, Registry::get('jwt_info')->id, $now_date, Registry::get('jwt_info')->id
            );
        } catch (ModelDriverException $e) {
            if ($e->getCode() == ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new AdException(AdException::AD_CREATE_FAILURE, AdException::AD_CREATE_FAILURE_NO);
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }


    /**
     * 编辑广告
     * @param array $parameters
     * @return array|mixed|null
     * @throws AdException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function edit($parameters = [])
    {
        try {
            if (!isset($parameters['id']) || empty($parameters['id']))
                throw new AdException(AdException::AD_ID_IS_EMPTY, AdException::AD_ID_IS_EMPTY_NO);

            $update_arr = [];
            if (isset($parameters['name']))
                $update_arr['name'] = $parameters['name'];
            if (isset($parameters['img']))
                $update_arr['img'] = str_replace(Registry::get('config')['application']['host'], '', $parameters['img']);
            if (isset($parameters['type']))
                $update_arr['type'] = $parameters['type'];
            if (isset($parameters['ad_addr_type']))
                $update_arr['ad_addr_type'] = $parameters['ad_addr_type'];
            if (isset($parameters['ad_addr']))
                $update_arr['ad_addr'] = $parameters['ad_addr'];
            if (isset($parameters['status']))
                $update_arr['status'] = $parameters['status'];
            if (isset($parameters['past_time']))
                $update_arr['past_time'] = $parameters['past_time'];
            if (isset($parameters['order']))
                $update_arr['order'] = $parameters['order'];

            if (!empty($update_arr)) {
                $update_arr['updated_at'] = date('Y-m-d H:i:s', time());
                $update_arr['updated_by'] = Registry::get('jwt_info')->id;
                $result                   = ADService::getInstance()->update($update_arr, $parameters['id']);

            } else
                $result = ADService::getInstance()->getOne($parameters['id']);

            return $result;
        } catch (AdException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            if ($e->getCode() == ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new AdException(AdException::AD_EDIT_FAILURE, AdException::AD_EDIT_FAILURE_NO);
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }

    }

    /**
     * 广告列表
     * @param array $parameters
     * @return array|mixed
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getAdList($parameters = [])
    {
        try {
            $from_api = isset($parameters['from_api']) && $parameters['from_api'] === true;
            $groups = $g_rules = $rules = $condition = [];

            if (isset($parameters['type']))
                array_push($rules, ['field' => 'type', 'op' => 'eq', 'data' => $parameters['type']]);
            if (isset($parameters['ad_addr_type']))
                array_push($rules, ['field' => 'ad_addr_type', 'op' => 'eq', 'data' => $parameters['ad_addr_type']]);
            if (isset($parameters['status']))
                array_push($rules, ['field' => 'status', 'op' => 'eq', 'data' => $parameters['status']]);
            if (isset($parameters['id']))
                array_push($rules, ['field' => 'id', 'op' => 'ne', 'data' => $parameters['id']]);
            if (isset($parameters['name']))
                array_push($rules, ['field' => 'name', 'op' => 'eq', 'data' => $parameters['name']]);
            if (isset($parameters['start_expired_date']))
                array_push($rules, ['field' => 'past_time', 'op' => 'ge', 'data' => date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', $parameters['start_expired_date'])))]);
            if (isset($parameters['end_expired_date']))
                array_push($rules, ['field' => 'past_time', 'op' => 'le', 'data' => date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', $parameters['end_expired_date'])))]);
            if (isset($parameters['expire']))
                array_push($rules, ['field' => 'past_time', 'op' => 'eq', 'data' => '0000-00-00 00:00:00']);

            // 客户端调用 status=1 and past_time >= current_time or past_time = '0000-00-00 00:00:00"
            if ($from_api === true) {
                array_push($rules, ['field' => 'status', 'op' => 'eq', 'data' => 1]);
                array_push($g_rules, ['field' => 'past_time', 'op' => 'eq', 'data' => '0000-00-00 00:00:00']);
                array_push($g_rules, ['field' => 'past_time', 'op' => 'ge', 'data' => date('Y-m-d H:i:s', time())]);
                $groups = [['groupOp' => 'OR', 'rules' => $g_rules]];
            }
            /*if (isset($parameters['past_status'])) {
                if ($parameters['past_status'] == 1) {
                    array_push($g_rules, ['field' => 'past_time', 'op' => 'eq', 'data' => 0]);
                    array_push($g_rules, ['field' => 'past_time', 'op' => 'ge', 'data' => date('Y-m-d H:i:s', time())]);
                    $groups = [['groupOp' => 'OR', 'rules' => $g_rules]];
                } else
                    array_push($rules, ['field' => 'past_time', 'op' => 'lt', 'data' => date('Y-m-d H:i:s', time())]);

            }*/

            if (!empty($rules)) {
                $condition = ['groupOp' => 'AND', 'rules' => $rules, 'groups' => $groups];
            } else {
                if ($groups) {
                    $condition = ['groupOp' => 'OR', 'rules' => $g_rules];
                }
            }
//            print_r($condition);exit;
            $ad_list = AdService::getInstance()->getList(
                isset($parameters['page']) ? $parameters['page'] : 1,
                isset($parameters['page_size']) ? $parameters['page_size'] : 10,
                isset($parameters['sort']) ? $parameters['sort'] : 'desc',
                isset($parameters['order']) ? $parameters['order'] : 'order',
                $condition
            );

            // 后台接口 需要获取广告创建者与广告编辑者的mobile
            if ($from_api === false)
                $ad_list = User::getUsersByModule($ad_list);

            foreach ($ad_list['data'] as $idx => $ad_info) {
                $ad_list['data'][$idx]['type'] = (int)$ad_info['type'];
                $ad_list['data'][$idx]['ad_addr_type'] = (int)$ad_info['ad_addr_type'];
                $ad_list['data'][$idx]['status'] = (int)$ad_info['status'];
                $ad_list['data'][$idx]['ad_one_pop'] = (int)$ad_info['ad_one_pop'];
                $ad_list['data'][$idx]['img'] = Registry::get('config')['application']['host'] . $ad_info['img'];
            }

            return $ad_list;
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }

    }

    /**
     * 删除广告
     * @param int $ad_id
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     */
    public function deleteAd($ad_id = 0) {
        try {
            AdService::getInstance()->delete($ad_id);
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        }
    }

    /**
     * 批量删除ad
     * @param array $id_arr
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws AdException
     */
    public function batchDeleteAds($id_arr = []) {

        try {
            if (empty($id_arr))
                throw new AdException(AdException::AD_ID_IS_EMPTY, AdException::AD_ID_IS_EMPTY_NO);

            ADService::getInstance()->batchDelete($id_arr);

        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (AdException $e) {
            throw $e;
        }
    }
}
